#!/usr/bin/env python2

#import rpchelp
import poncrpc.rpc as rpc
import sys, os
import traceback
import random

from ns2 import *

def make_anchor(lpath):
	anid = random.getrandbits(32) & 0xFFFFFFFF
	fnam = "%s/..MOTE..%u" % (lpath, anid)
	print "Anchoring", fnam,
	try:
		fd = os.open(fnam, os.O_CREAT, 0644)
	except OSError, E:
		print "no way"
#		traceback.print_exc()
		return None
	print "done"
	os.fsync(fd) # make sure the client sees it
	try:
		os.unlink(fnam)
	except OSError:
		pass
	return anid

def spec2str(spec):
	if spec.type == MFS2MOUNT_FROZEN:
		return "sesn:%u" % spec._data
	elif spec.type == MFS2MOUNT_SNAP:
		return "snap:%u" % spec._data.snid
	raise "Bad spec"

def desc2str(desc):
	if desc.type == MFS2MOUNT_DIRECT:
		return spec2str(desc._data)
	elif desc.type == MFS2MOUNT_DIRECT:
		return ispec2str(desc._data)
	raise "Bad descriptor"

class NS2Client(NAMESPACE_2_Stubs, rpc.TCPClient):
	def __init__(self, host='localhost'):
		rpc.TCPClient.__init__(self, host, NAMESPACE_2.prog, 2)
	def do_snap(self, lpath):
		anid = make_anchor(lpath)
		if anid is None:
			return None
		oldnsnum = self.probens(anid)
		res = self.snapone(anid, '/', False, '')
		if res.status == NS2_OK:
			print res._data.__slots__
			print "Snap OK",
			print ":".join((res._data.server, desc2str(res._data.desc),
						   res._data.path))
		else:
			print "Mount failed", res.status

ns2c = NS2Client()

res = ns2c.make_call(108, None,
					 None,
					 ns2c.unpacker.unpack_hyper)
print res

res = ns2c.make_call(110, 1,
					 ns2c.packer.pack_uint32_t,
					 ns2c.unpacker.unpack_nsinfo_res)
print res


ns2c.do_snap(sys.argv[1])
